package org.mch.comm.db.exphandler;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.mch.comm.lang.MDate;
import org.mch.comm.velocity.MVelocityEngine;
import org.mch.comm.velocity.VelBeanData;
import org.mch.comm.velocity.VelFieldData;
import org.mch.func.db.tool.DBInfoUtil;
import org.mch.func.entity.TableColumnEO;

/**
 * 描述：
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class ExpRSBaseEOHandler extends ExpRSSQLHandler {
	private static final long serialVersionUID = -7789407398860275492L;

	public ExpRSBaseEOHandler(int dbmsType, String tableName) {
		super(dbmsType, tableName);
	}

	protected String buildClassName() {
		String tablecode = firstLetterUpperCase(getTableName().toLowerCase()) + "EO";
		String[] tmp = tablecode.split("_");
		if (tmp != null && tmp.length > 1) {
			StringBuffer tmpcode = new StringBuffer();
			for (int i = 0; i < tmp.length; i++) {
				if (i == 0) {
					tmpcode.append(tmp[i]);
				} else {
					tmpcode.append(firstLetterUpperCase(tmp[i]));
				}
			}
			return tmpcode.toString();
		}
		return tablecode;
	}

	public String handler(ResultSet rs) throws Exception {

		Map<String, TableColumnEO> types = DBInfoUtil.getColmnTypes(getTableName());

		String str = this.handle(types);

		return str;
	}

	public String handle(Map<String, TableColumnEO> types) throws Exception {
		if (types == null) {
			return "";
		}
		String table_pk = DBInfoUtil.getTablePKField(getTableName());

		String[] fieldnames = (String[]) types.keySet().toArray(new String[0]);

		String beanClassName = buildClassName();

		VelBeanData beanData = new VelBeanData();
		beanData.setPKFieldName(table_pk);
		beanData.setTableName(getTableName());
		beanData.setVersionUID(System.nanoTime() + "L");
		beanData.setClassName(beanClassName);
		beanData.setAuthorName("ZL");
		beanData.setCreateDate(new MDate(new Date()).toString());

		List<VelFieldData> fieldList = new ArrayList<VelFieldData>();
		beanData.setFieldList(fieldList);

		for (int i = 0; i < fieldnames.length; i++) {
			VelFieldData fieldData = new VelFieldData();
			TableColumnEO colinfo = types.get(fieldnames[i]);
			String colname = fieldnames[i].toLowerCase();
			String coltypestr = byColTypeGetJavaBeanJavaType(colinfo.coltype, colinfo.precision, colinfo.scale);

			fieldData.setFieldDesc(colname);
			fieldData.setFieldModifier("private");
			fieldData.setFieldName(colname);
			fieldData.setFieldType(coltypestr);

			fieldData.setMethodGetName("get" + firstLetterUpperCase(colname));
			fieldData.setMethodSetName("set" + firstLetterUpperCase(colname));

			fieldList.add(fieldData);
		}

		return new MVelocityEngine().getTemplateStrEO("resource/vmtemplate/BaseEO.vm", beanData);
	}

	public String firstLetterUpperCase(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
	}

}